/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package service;

import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import jpa.entities.ItemPedido;
import jpa.entities.Pedido;
import jpa.entities.Usuario;
import java.util.Collection;
import converter.PedidoConverter;
import javax.ejb.Stateless;

/**
 *
 * @author carlos
 */

@Stateless
public class PedidoResource {
    @javax.ejb.EJB
    private ItemPedidoCollectionResourceSub itemPedidoCollectionResourceSub;
    @javax.ejb.EJB
    private UsuarioResourceSub usuarioResourceSub;
    @Context
    protected UriInfo uriInfo;
    protected EntityManager em;
    protected Integer id;
  
    /** Creates a new instance of PedidoResource */
    public PedidoResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    /**
     * Get method for retrieving an instance of Pedido identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of PedidoConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public PedidoConverter get(@QueryParam("expandLevel")
                               @DefaultValue("1")
    int expandLevel) {
        return new PedidoConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
    }

    /**
     * Put method for updating an instance of Pedido identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an PedidoConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(PedidoConverter data) {
        updateEntity(getEntity(), data.resolveEntity(em));
    }

    /**
     * Delete method for deleting an instance of Pedido identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        deleteEntity(getEntity());
    }

    /**
     * Returns an instance of Pedido identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Pedido
     */
    protected Pedido getEntity() {
        try {
            return (Pedido) em.createQuery("SELECT e FROM Pedido e where e.idPedido = :idPedido").setParameter("idPedido", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    private Pedido updateEntity(Pedido entity, Pedido newEntity) {
        Usuario usuario = entity.getUsuario();
        Usuario usuarioNew = newEntity.getUsuario();
        Collection<ItemPedido> itemPedidoCollection = entity.getItemPedidoCollection();
        Collection<ItemPedido> itemPedidoCollectionNew = newEntity.getItemPedidoCollection();
        entity = em.merge(newEntity);
        if (usuario != null && !usuario.equals(usuarioNew)) {
            usuario.getPedidoCollection().remove(entity);
        }
        if (usuarioNew != null && !usuarioNew.equals(usuario)) {
            usuarioNew.getPedidoCollection().add(entity);
        }
        for (ItemPedido value : itemPedidoCollection) {
            if (!itemPedidoCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from itemPedidoCollection"));
            }
        }
        for (ItemPedido value : itemPedidoCollectionNew) {
            if (!itemPedidoCollection.contains(value)) {
                Pedido oldEntity = value.getPedido();
                value.setPedido(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getItemPedidoCollection().remove(value);
                }
            }
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    private void deleteEntity(Pedido entity) {
        Usuario usuario = entity.getUsuario();
        if (usuario != null) {
            usuario.getPedidoCollection().remove(entity);
        }
        if (!entity.getItemPedidoCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because itemPedidoCollection is not empty."));
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of UsuarioResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of UsuarioResource
     */
    @Path("usuario/")
    public UsuarioResource getUsuarioResource() {
        usuarioResourceSub.setParent(getEntity());
        return usuarioResourceSub;
    }

    /**
     * Returns a dynamic instance of ItemPedidoesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of ItemPedidoesResource
     */
    @Path("itemPedidoCollection/")
    public ItemPedidoesResource getItemPedidoCollectionResource() {
        itemPedidoCollectionResourceSub.setParent(getEntity());
        return itemPedidoCollectionResourceSub;
    }

    @Stateless(name = "PedidoResource.UsuarioResourceSub")
    public static class UsuarioResourceSub extends UsuarioResource {

        private Pedido parent;

        public void setParent(Pedido parent) {
            this.parent = parent;
        }

        @Override
        protected Usuario getEntity() {
            Usuario entity = parent.getUsuario();
            if (entity == null) {
                throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
            }
            return entity;
        }
    }

    @Stateless(name = "PedidoResource.ItemPedidoCollectionResourceSub")
    public static class ItemPedidoCollectionResourceSub extends ItemPedidoesResource {

        private Pedido parent;

        public void setParent(Pedido parent) {
            this.parent = parent;
        }

        @Override
        protected Collection<ItemPedido> getEntities(int start, int max, String query) {
            Collection<ItemPedido> result = new java.util.ArrayList<ItemPedido>();
            int index = 0;
            for (ItemPedido e : parent.getItemPedidoCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}
